#include "client.h"

int FileExist(char* pathName, char* srcName, char* destName) {
    //将源路径和目标路径分开
    int lengthOfPath = strlen(pathName);
    int j;
    for(j = 0; j < lengthOfPath; j++) {
        if(pathName[j] == ' ') {
            break;
        }
    }
    memcpy(srcName, pathName, j);
    while(pathName[j] == ' ') {
        j++;
    }
    strcpy(destName, pathName + j);
    //去掉前置和后置的/
    int lengthOfSrc = strlen(srcName);
    int lengthOfDest = strlen(destName);
    if(srcName[lengthOfSrc - 1] == '/') {
        srcName[lengthOfSrc - 1] = 0;
        lengthOfSrc--;
    }
    if(srcName[0] == '/') {
        memmove(srcName, srcName + 1, lengthOfSrc - 1);
        lengthOfSrc--;
    }
    if(destName[lengthOfDest - 1] == '/') {
        destName[lengthOfDest - 1] = 0;
        lengthOfDest--;
    }
    if(srcName[0] == '/') {
        memmove(destName, destName + 1, lengthOfDest - 1);
        lengthOfDest--;
    }
    //将文件名从文件路径中分离出来
    char dirPath[1000] = {0};
    char fileName[1000] = {0};
    for(int i = lengthOfSrc - 1; i >= 0; i--) {
        if(srcName[i] == '/') {
            memcpy(dirPath, srcName, i);
            strcpy(fileName, srcName + i + 1);
        }
    }
    if(strlen(fileName) == 0) {
        dirPath[0] == '.';
        strcpy(fileName, srcName);
    }
    //printf("%s, %s, %s, %s\n", srcName, destName, dirPath, fileName);
    //判断文件是否存在，并设标志位fileExist
    //如果存在则向服务器发送相关信息，不存在则返回-1
    int ret = CheckExist(dirPath, fileName);
    if(ret == -1){
        printf("no such file.\n");
    }
    
    return 0;
}





//判断文件是否存在，并设标志位fileExist
//如果存在则向服务器发送相关信息，不存在则返回-1
int CheckExist(char* dirPath, char* fileName){

    int fileExist = 0;
    DIR* dirp = opendir(dirPath);

    if(dirp == NULL) {
        perror("opendir");
        return -1;
    }
    struct dirent* entry = readdir(dirp);
    while(entry) {
        if(!strcmp(entry->d_name, fileName)) {
            fileExist = 1;
            break;
        }
        entry = readdir(dirp);
    }

    //如果存在则向服务器发送相关信息，不存在则返回-1
    if(fileExist == 0) {
        return -1;
    }
}

